﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;

namespace ZJF.Anonymous._01_自定义泛型委托
{
    public class MyGenericDelegate
    {
        /// <summary>
        /// 自定义泛型委托使用测试
        /// </summary>
        public static void Test1()
        {
            //【1】使用泛型委托关联具体方法
            CalculateAdd<int> calc = new CalculateAdd<int>(Add);
            Console.WriteLine(calc(1, 2));

            CalculateAdd<double> calc2 = new CalculateAdd<double>(Sub);
            Console.WriteLine(calc2(1.0, 2));

            // 【2】使用泛型委托关联匿名方法
            CalculateAdd<int> calc3 = delegate (int x, int y) { return x + y; };
            CalculateAdd<double> calc4 = delegate (double x, double y) { return x - y; };
            Console.WriteLine(calc3(1, 2));
            Console.WriteLine(calc4(1.0, 2));


            // 【3】 使用泛型委托关联lambda表达式
            CalculateAdd<int> calc5 = (x, y) => { return x + y; };
            CalculateAdd<double> calc6 = (x, y) => { return x - y; };
            Console.WriteLine(calc5(1, 2));
            Console.WriteLine(calc6(1.0, 2));
        }

        public static int Add(int x, int y)
        {
            return x + y;
        }

        public static double Sub(double x, double y)
        {
            return x - y;
        }

        public static void SayHi(string name) {
            Console.WriteLine($"say Hi to {name}!");
        }

        public static string Introduciton(string name) {
            return $"{name} 的个人简介";
        }

        /// <summary>
        ///  系统泛型委托
        /// </summary>
        public static void Test2() {
            // 【1.1】 Action关联具体方法
            Action<string> action1 = new Action<string>(SayHi);
            // 【1.2】 Action关联匿名方法
            Action<string> action2 = delegate (string name) { Console.WriteLine($"say hi to {name}"); };

            // 【1.3】Action关联lambda表达式
            Action<string, string> action3 = (name, addr) => { Console.WriteLine($"{name} 的家庭地址是：{addr}"); };

            // 【2.1】 Func关联具体方法
            Func<string, string> action4 = new Func<string, string>(Introduciton);

            // 【2.2】 Func关联匿名方法
            Func<string, string> action5 = delegate (string name) { return $"{name} 的个人简介"; };

            // 【2.3】 Func关联lambda表单式
            Func<string, string> action6 = (name) => { return $"{name} 的个人简介"; };

            // 统一测试
            action1("张三");
            action2("张三");
            action3("张阿", "北京");
            var result = action4("李四");
            Console.WriteLine(result);
            result = action5("李四");
            Console.WriteLine(result);
            result = action6("李四");
            Console.WriteLine(result);
        }

    }

    // 【1】自定义泛型委托
    public delegate T CalculateAdd<T>(T x, T y);
}
